import Realm from 'realm';

const schemaPath = "mes.realm"


/**
 * 应用表
 */
 const AppInfo = {
    name: 'AppInfo',
    primaryKey: "appId", // 定义主键后，无法创建同一主键的数据
    properties: {
        appId: 'int',
        appName: 'string',
        appHisId: 'int',
        // sort: 'int',
        appDesc: 'string',
        platform: 'string',
        version: 'string',
        appLogo: 'string',
        distributeDate:'string',
        appType: 'string',
        target: 'string',
        appTypeId: 'int',
        appFilePath: 'string',
        localPath:'string'

        // newTitle: 'string',  //版本2新增
        // newTitle2: 'string'  //版本3新增

    }
};


var UpgradeMigrations = [
    {
        schema:[
            AppInfo
        ],
        path: schemaPath,
        schemaVersion:1
       
    }
    ,{
        schema:[
            AppInfo
        ],
        path:schemaPath,
        schemaVersion:2,
        migration:(oldRealm, newRealm)=>{
            // 只有当schemaVersion小于1的时候才会执行if中代码
            if(oldRealm.schemaVersion < 2){
                const oldObjects = oldRealm.objects('AppInfo');
                const newObjects = newRealm.objects('AppInfo');
 
                // 遍历所有对象，并将新的模型中设置属性
                // for (let i = 0; i < oldObjects.length; i++) {
                //     newObjects[i].newTitle = '';
                //     // Alert.alert('ssss',  newObjects[i].newTitle);
                // }
            }
        }
    },
    // {
    //     schema:[
    //         AppInfo
    //     ],
    //     path:schemaPath,
    //     schemaVersion:3,
    //     migration:(oldRealm, newRealm)=>{
    //         // 只有当schemaVersion小于3的时候才会执行if中代码
    //         if(oldRealm.schemaVersion < 3){
    //             const oldObjects = oldRealm.objects('AppInfo');
    //             const newObjects = newRealm.objects('AppInfo');
 
    //             // 遍历所有对象，并将新的模型中设置属性
    //             for (let i = 0; i < oldObjects.length; i++) {
    //                 newObjects[i].newTitle2 = '';
    //                 // Alert.alert('ssss',  newObjects[i].testTitle);
    //             }
    //         }
    //     }
    // }
];

export const clearCache = () => {
    realm.write(() => {
        realm.deleteAll()
    })
};



//获取被给予路径的Realm的版本号
let nextSchemaIndex = Realm.schemaVersion(schemaPath);
 
//保证不同版本Realm升级，执行不同Realm版本迁移升级
if (nextSchemaIndex != -1) {
    while (nextSchemaIndex < UpgradeMigrations.length) {
        //  var migratedRealm = new Realm(schemas[nextSchemaIndex++]);
        //   migratedRealm.close();
        // const migratedRealm = new Realm({...UpgradeMigrations[nextSchemaIndex] });
        const migratedRealm = new Realm(UpgradeMigrations[nextSchemaIndex++]);
        // nextSchemaIndex += 1;
        migratedRealm.close();
    }
}
 
//获取当前版本的Realm
let realm = new Realm(UpgradeMigrations[UpgradeMigrations.length - 1]);

export default realm;
